import { computed, ref } from 'vue';
import {
  updateEntity,
  deleteEntity,
  resetPassword,
} from '@/api/dashboard/users';
import { getDict } from '@/api/base';
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import { Modal, Message } from '@arco-design/web-vue';
import { validateForm } from '@/utils';

export let modalType = ref(0);
export let currRecord = ref({} as any);

export let parType = ref([] as SelectOptionData[]);
export let parType2 = ref([] as SelectOptionData[]);

(async function () {
  let data = await getDict(10, 'UserTypes');
  parType.value = data;

  let data2 = await getDict(10, 'AccountTypes');
  parType2.value = data2;
})();

export function addNew() {
  modalType.value = 3;
  currRecord.value = {
    enabled: true,
  };
  validateForm(null, true);
}

export let currSelect = ref(0);
export function rowSelect(rowKeys: Array<number>, key: number, record: any) {
  currSelect.value = key;
  currRecord.value = record;
}

export function btnView(record: any) {
  modalType.value = 1;
  currRecord.value = record;
}

export function btnResetPassword() {
  console.log('user', currSelect.value);
  if (!currSelect.value) {
    Message.warning('请先选择一行');
    return;
  }
  Modal.confirm({
    title: '确认',
    content: `确定要重置【${currRecord.value.userName}】的登录密码吗？`,
    onOk: async function () {
      resetPassword(currSelect.value)
        .then(function (res) {
          Message.success('重置成功');
        })
        .catch((error) => {
          console.log(error);
          Message.warning('重置失败');
        });
    },
  });
  console.log(currSelect.value);
}


export function btnEdit(record: any) {
  modalType.value = 2;
  currRecord.value = { ...record };
  validateForm(null, true);
}

export function btnDelete(record: any, call: Function) {
  Modal.confirm({
    title: '确认',
    content: `确定要删除【${record.userName}】吗？`,
    onOk: async function () {
      await deleteEntity(record.userId);
      call();
    },
  });
}

export async function btnEditSave(call: Function) {
  if (!validateForm()) {
    return;
  }
  modalType.value = 0;
  await updateEntity(currRecord.value);
  call();
}

export let roleVisible = ref(false);
export function showRoles() {
  if (!currSelect.value) {
    Message.warning('请先选择一行');
    return;
  }
  roleVisible.value = true;
}

export let groupVisible = ref(false);
export function showGroups() {
  if (!currSelect.value) {
    Message.warning('请先选择一行');
    return;
  }
  groupVisible.value = true;
}
